package com.yj.suncity.user;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yj.suncity.R;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.publish.PicSelectActivity;
import com.yj.suncity.publish.SelectPicShowActivity;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.HttpUtil;
import com.yj.suncity.utis.ProgressUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.UploadUtil;
import com.yj.suncity.utis.UploadUtil.OnUploadProcessListener;

public class ShopImgsActivity extends Activity {
	private static final int FAIL = 1;
	private static final int IO_EXCEPTION = 3;
	private static final int JSON_EXCEPTION = 4;
	private static final int SUCCESS = 2;
	private ImageAdapter adapter;
	private StringBuffer buffer = new StringBuffer();
	private Context context;
	private String entId;
	private GridView gridView;

	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case FAIL:
				progressUtil.ShowProgress(context, false, false, "正在修改......");
				ToastUtil.ShowToast(context, "" + (String) msg.obj);
				break;
			case SUCCESS:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, "上传成功！");
				Intent localIntent = new Intent();
				if (!ShopImgsActivity.this.shopImgs.equals(""))
				{					
					if (ShopImgsActivity.this.shopImgs.contains(","))
					{						
						localIntent
						.putExtra("size",
								ShopImgsActivity.this.shopImgs
								.split(",").length);
					}
					else{
						localIntent
						.putExtra("size",
								1);
					}
				}else{
					localIntent
					.putExtra("size",
							0);
				}
					localIntent.putExtra("imgpaths",
							ShopImgsActivity.this.shopImgs);
					ShopImgsActivity.this.setResult(1001, localIntent);
					ShopImgsActivity.this.finish();

				break;
			case IO_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, "网络异常！");
				break;
			case JSON_EXCEPTION:
				progressUtil.ShowProgress(context, false, false, "正在上传......");
				ToastUtil.ShowToast(context, "数据解析异常！");
				break;
			default:
				break;
			}
		};
	};

	private DisplayImageOptions options;
	private List<NameValuePair> pairs;
	private String picPath;
	private ProgressUtil progressUtil;
	private String shopImgs = "";
	private ArrayList<String> uploadPaths;
	private int width;

	private void findView() {
		this.progressUtil = new ProgressUtil();
		this.gridView = ((GridView) findViewById(R.id.gridView1));
		this.adapter = new ImageAdapter(this.uploadPaths, this.context);
		this.gridView.setAdapter(this.adapter);
	}

	private String getPhotoFileName() {
		Date localDate = new Date(System.currentTimeMillis());
		return new SimpleDateFormat("'IMG'yyyyMMddHHmmss").format(localDate)
				+ ".jpg";
	}

	private void popView() {
		DialogUtils.getInstance().SelectPicDialog(this.context,
				new DialogUtils.ItemCall() {
					public void onIndexCall(int paramAnonymousInt) {
						if (paramAnonymousInt == 0)
							ShopImgsActivity.this.startPaizhao();
						while (paramAnonymousInt != 1)
							return;
						ShopImgsActivity.this.startXiangce();
					}
				});
	}

	private void startPaizhao() {
		if (Environment.getExternalStorageState().equals("mounted")) {
			Intent localIntent = new Intent(
					"android.media.action.IMAGE_CAPTURE");
			String str = getPhotoFileName();
			this.picPath = (Environment.getExternalStorageDirectory()
					+ "/DCIM/Camera/" + str);
			File localFile = new File(this.picPath);
			if (!localFile.exists())
				;
			try {
				localFile.createNewFile();
				localIntent.putExtra("output", Uri.fromFile(localFile));
				startActivityForResult(localIntent, 110);
				return;
			} catch (IOException localIOException) {
				while (true) {
					Log.d("", localIOException.getMessage());
					localIOException.printStackTrace();
				}
			}
		}
		ToastUtil.ShowToast(this.context, "内存卡不存在！");
	}

	private void startXiangce() {
		Intent localIntent = new Intent(this.context, PicSelectActivity.class);
		localIntent.putExtra("picPathSize", this.uploadPaths.size());
		startActivityForResult(localIntent, 103);
	}

	private void updateInfo() {
		this.pairs.clear();
		this.pairs.add(new BasicNameValuePair("action", "modifyentinfo"));
		this.pairs.add(new BasicNameValuePair("id", this.entId));
		this.pairs.add(new BasicNameValuePair("img", this.shopImgs));
		new Thread(new Runnable() {
			public void run() {
				try {
					JSONObject localJSONObject = new JSONObject(
							HttpUtil.HttpClientdoPost(
									URLCon.用户,
									ShopImgsActivity.this.pairs));
					if (localJSONObject.optString("success").equals("1")) {
						Message localMessage3 = new Message();
						localMessage3.what = 2;
						ShopImgsActivity.this.handler
								.sendMessage(localMessage3);
						return;
					}
					Message localMessage4 = new Message();
					localMessage4.what = 1;
					localMessage4.obj = localJSONObject.optString("msg");
					ShopImgsActivity.this.handler.sendMessage(localMessage4);
					return;
				} catch (IOException localIOException) {
					Message localMessage2 = new Message();
					localMessage2.what = 3;
					ShopImgsActivity.this.handler.sendMessage(localMessage2);
					localIOException.printStackTrace();
					return;
				} catch (JSONException localJSONException) {
					Message localMessage1 = new Message();
					localMessage1.what = 4;
					ShopImgsActivity.this.handler.sendMessage(localMessage1);
					localJSONException.printStackTrace();
				}
			}
		}).start();
	}

	protected void onActivityResult(int paramInt1, int paramInt2,
			Intent paramIntent) {
		if (paramInt1 == 110) {
			this.uploadPaths.add(this.picPath);
			if (this.uploadPaths.size() > 9) {
				this.uploadPaths.remove(this.picPath);
				ToastUtil.ShowToast(this.context, "您最多可以选择9张图片！");
				return;
			}
			this.adapter.notifyDataSetChanged();
		}
		if ((paramInt1 == 103) && (paramInt2 == 104)) {
			this.uploadPaths.clear();
			this.adapter.notifyDataSetChanged();
		}
		if ((paramInt1 == 103) && (paramInt2 == 103)) {
			ArrayList localArrayList2 = paramIntent
					.getStringArrayListExtra("picPaths");
			if ((localArrayList2 != null) && (localArrayList2.size() > 0)) {
				this.uploadPaths.clear();
				this.uploadPaths.addAll(localArrayList2);
				HashSet localHashSet2 = new HashSet(this.uploadPaths);
				this.uploadPaths.clear();
				this.uploadPaths.addAll(localHashSet2);
				this.adapter.notifyDataSetChanged();
			}
		}
		if ((paramInt1 == 103) && (paramInt2 == 105)) {
			ArrayList localArrayList1 = paramIntent
					.getStringArrayListExtra("picPaths");
			if ((localArrayList1 != null) && (localArrayList1.size() > 0)) {
				this.uploadPaths.addAll(localArrayList1);
				HashSet localHashSet1 = new HashSet(this.uploadPaths);
				this.uploadPaths.clear();
				this.uploadPaths.addAll(localHashSet1);
				if (this.uploadPaths.size() > 9) {
					this.uploadPaths.removeAll(localArrayList1);
					ToastUtil.ShowToast(this.context, "您最多可以选择9张图片！");
					return;
				}
				this.adapter.notifyDataSetChanged();
			}
		}
		super.onActivityResult(paramInt1, paramInt2, paramIntent);
	}

	public void onClick(View paramView) {
		switch (paramView.getId()) {
		default:
			return;
		case R.id.btnHeadBack:
			finish();
			return;
		case R.id.btn_add_img:
			popView();
			return;
		case R.id.btn_submit:
			uploadImage();
		}
		
	}

	private void uploadImage() {
		Map<String, String> param = new HashMap<String, String>();
		param.put("action", "uploads");
		UploadUtil uploadUtil = new UploadUtil();
		progressUtil = new ProgressUtil();
		progressUtil.ShowProgress(context, true, false, "正在上传......");
		uploadUtil.uploadFile(context, uploadPaths, "txtimg", URLCon.图片上传,
				param, new OnUploadProcessListener() {
					@Override
					public void UploadResule(String result) {
						Log.d("", "result===" + result);
						try {
							JSONObject localJSONObject1 = new JSONObject(result);
							if (localJSONObject1.optString("success").equals(
									"1")) {
								JSONArray localJSONArray = localJSONObject1
										.optJSONArray("data");
								for (int i = 0; i < localJSONArray.length(); i++) {

									JSONObject localJSONObject2 = localJSONArray
											.optJSONObject(i);
									buffer.append(localJSONObject2
											.optString("url") + ",");
								}
								Log.d("haha",
										"\\\\"
												+ ShopImgsActivity.this.buffer
														.length()
												+ "======="
												+ ShopImgsActivity.this.buffer
														.toString());
								shopImgs = ShopImgsActivity.this.buffer
										.toString();
								updateInfo();

								return;

							} else {
								Message message = new Message();
								message.what = FAIL;
								message.obj = localJSONObject1.optString("msg");
								handler.sendMessage(message);
							}
						} catch (JSONException e) {
							Message message = new Message();
							message.what = JSON_EXCEPTION;
							handler.sendMessage(message);
							e.printStackTrace();
						}
					}
				});
	}

	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.activity_shop_img);
		this.context = this;
		this.pairs = new ArrayList();
		this.uploadPaths = getIntent().getStringArrayListExtra("paths");
		this.entId = getIntent().getStringExtra("entid");
		this.width = getResources().getDisplayMetrics().widthPixels;
		this.options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_detail)
				.showImageForEmptyUri(R.drawable.android_layout_detail)
				.showImageOnFail(R.drawable.android_layout_detail)
				.cacheInMemory(true).cacheOnDisc(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
		findView();
	}

	class ImageAdapter extends BaseAdapter {
		private Context context;
		private ImageLoader imageLoader;
		private List<String> imgPaths;

		public ImageAdapter(List<String> paths, Context context) {
			this.imgPaths = paths;
			this.context = context;
			this.imageLoader = ImageLoader.getInstance();
		}

		public int getCount() {
			return this.imgPaths.size();
		}

		public Object getItem(int paramInt) {
			return this.imgPaths.get(paramInt);
		}

		public long getItemId(int paramInt) {
			return paramInt;
		}

		public View getView(final int paramInt, View paramView,
				ViewGroup paramViewGroup) {
			ShopImgsActivity.ViewHolder localViewHolder;
			if (paramView == null) {
				localViewHolder = new ViewHolder();
				paramView = LayoutInflater.from(this.context).inflate(
						R.layout.pic_select_adapter, null);
				localViewHolder.imageView = ((ImageView) paramView
						.findViewById(R.id.imageView1));
				localViewHolder.imageView
						.setLayoutParams(new RelativeLayout.LayoutParams(
								ShopImgsActivity.this.width / 3,
								ShopImgsActivity.this.width / 3));
				localViewHolder.is_select = ((CheckBox) paramView
						.findViewById(R.id.is_show));
				localViewHolder.is_select.setVisibility(View.GONE);
				paramView.setTag(localViewHolder);
				if (this.imgPaths.size() > 0) {
					if (!((String) this.imgPaths.get(paramInt)).contains(ShareCon.SD)){
						imageLoader.displayImage(
								URLCon.HOST+ (String) this.imgPaths.get(paramInt),
								localViewHolder.imageView,
								ShopImgsActivity.this.options);
					}else{						
						this.imageLoader.displayImage("file://"
								+ (String) this.imgPaths.get(paramInt),
								localViewHolder.imageView,
								ShopImgsActivity.this.options);
					}
				}
			}else{
				localViewHolder = (ViewHolder)paramView.getTag();
			}
				localViewHolder.imageView
						.setOnClickListener(new View.OnClickListener() {
							public void onClick(View paramAnonymousView) {
								Intent localIntent = new Intent(
										ShopImgsActivity.ImageAdapter.this.context,
										SelectPicShowActivity.class);
								localIntent.putStringArrayListExtra("paths",
										ShopImgsActivity.this.uploadPaths);
								localIntent.putExtra("posi", paramInt);
								ShopImgsActivity.this.startActivityForResult(
										localIntent, 103);
							}
						});
				return paramView;
		}
	}

	public class ViewHolder {
		ImageView imageView;
		CheckBox is_select;

		ViewHolder() {
		}
	}
}